//
//  BinningEastShowCell.m
//  CJRailTransport
//
//  Created by Hank on 2017/12/29.
//  Copyright © 2017年 amplity. All rights reserved.
//

#import "BinningEastShowCell.h"
#import "DrCorner.h"
#import "BinningMerchandiseCarCell.h"
#import "BinningContainerCell.h"
#import "JSONTransition.h"
#import "NetWorkManager.h"
#import "RailTransportDao.h"
#import "MAAFConfig.h"

// 交互状态(可以交互,不可以交互,忽略交互)
typedef NS_ENUM(NSUInteger, UserInteractionEnabledState) {
    MayUserInteractionEnabled = 0,
    MayNotUserInteractionEnabled,
    IgnoreUserInteractionEnabled
};
// 按钮状态(自己按钮状态,其他按钮状态,按钮状态不改变)
typedef NS_ENUM(NSUInteger, BtnStateChange) {
    SelfStateChange = 0,
    OtherStateChange,
    BtnStateNotChange
};

@implementation BinningEastShowCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    // 更新约束后的Frame
    [self.contentView setNeedsLayout];
    [self.contentView layoutIfNeeded];
    // 设置圆角
    [self setRadius];
}
// 设置圆角
- (void)setRadius
{
    // 设置圆角
    [self.stentsNumberOneBg dr_addCornerRadius:3 borderWidth:0.5 backgroundColor:[UIColor clearColor] borderCorlor:[UIColor blackColor]];
    [self.stentsNumberTwoBg dr_addCornerRadius:3 borderWidth:0.5 backgroundColor:[UIColor clearColor] borderCorlor:[UIColor blackColor]];
    [self.saveBtn dr_addCornerRadius:3 borderWidth:0 backgroundColor:HEXCOLOR(kColorGray7, 1) borderCorlor:[UIColor clearColor]];
    [self.uploadBtn dr_addCornerRadius:3 borderWidth:0 backgroundColor:HEXCOLOR(kColorOrange4, 1) borderCorlor:[UIColor clearColor]];
}
// 设置圆角弧度和背景颜色
- (void)radiusbtn:(UIButton *)button cornerRadius:(CGFloat)cornerRadius backgroundColor:(UIColor *)backgroundColor
{
    button.layer.cornerRadius = cornerRadius;
    button.layer.backgroundColor = backgroundColor.CGColor;
}
// 去除分割线
- (UIView *)lineView
{
    return [[UIView alloc]init];
}

#pragma mark - Action
// 顶部支架按钮_1 Action
- (IBAction)topStentsBtnOneAction:(UIButton *)sender
{
    [self selectStateBtn:sender type:0];
}
// 顶部支架按钮_2 Action
- (IBAction)topStentsBtnTwoAction:(UIButton *)sender
{
     [self selectStateBtn:sender type:2];
}
// 底部支架按钮_1 Action
- (IBAction)bottomStentsBtnOneAction:(UIButton *)sender
{
    [self selectStateBtn:sender type:1];
}
// 底部支架按钮_2 Action
- (IBAction)bottomStentsBtnTwoAction:(UIButton *)sender
{
    
}
// 保存按钮 Action
- (IBAction)saveBtnAction:(UIButton *)sender
{
    // ============清除全部功能==========
//    // 清除商品车
//    for (int i = 0; i < self.merchandiseLabelArray.count; i++) {
//        UILabel *merchandiseCarLabel = self.merchandiseLabelArray[i];
//        merchandiseCarLabel.text = DefaultCommercial;
//    }
//    // 清除集装箱
//    for (int i = 0; i < self.containerLabelArray.count; i++) {
//        UILabel *containerLabel = self.containerLabelArray[i];
//        containerLabel.text = [[self.containerDataArray[i] allValues]firstObject];
//    }
//    // 清除核对示意图
//    for (int i = 0; i < self.schematicDiagramLabelArray.count; i++) {
//        UILabel *schematicDiagramLabel = self.schematicDiagramLabelArray[i];
//        schematicDiagramLabel.text = @"";
//    }
//    // 清楚集装箱编号
//    self.containerTF.text = @"";
//    // 清除按钮状态
//    [self clearBtnState];
    
    // ============保存到本地==========
    // 校验集装箱编号
    if (JudgeStrEqualNull(self.containerTF.text)) {
        [MBProgressHUD showError:ContainerPrompt];
        return;
    }
    
    BinningEastModel *binningEastModel = [[BinningEastModel alloc]init];
    binningEastModel.containerNo = self.containerTF.text;
    // 获取商品车编号
    NSMutableArray *carVINArray = [[NSMutableArray alloc]init];
    for (int i = 0; i < 4; i++) {
        UILabel *merchandiseCarLabel = self.merchandiseLabelArray[i];
        [carVINArray addObject:merchandiseCarLabel.text];
    }
    binningEastModel.carVIN = [carVINArray componentsJoinedByString:@","];
    binningEastModel.leftStentsNo = self.stentsOneNumber.text;
    binningEastModel.rightStentsNo = self.stentsTwoNumber.text;
    // 左右支架GPS
    for (int i = 0; i < self.GPSLabelArray.count; i++) {
        UILabel *stentsGPS = self.GPSLabelArray[i];
        if (i == 0) {
            binningEastModel.leftStentsGPSNo = stentsGPS.text;
        }else{
            binningEastModel.rightStentsGPSNo = stentsGPS.text;
        }
    }
    
    binningEastModel.putSequence = [NSString stringWithFormat:@"%@,%@,%@,%@",
                                    [[[self getMerchandiseVIN:self.topStentsBtnOneArray] allKeys]firstObject],
                                    [[[self getMerchandiseVIN:self.bottomStentsBtnOneArray] allKeys]firstObject],
                                    [[[self getMerchandiseVIN:self.topStentsBtnTwoArray] allKeys]firstObject],
                                    [[[self getMerchandiseVIN:self.bottomStentsBtnTwoArray] allKeys]firstObject]];
    binningEastModel.directionNo = self.trainShiftModel.departDirection;
    binningEastModel.date = [self.trainShiftModel.date stringByReplacingOccurrencesOfString:@"-" withString:@""];
    binningEastModel.location = self.trainShiftModel.location;
    binningEastModel.supplier = self.trainShiftModel.supplier;
    // 用户ID 测试暂时写101
    binningEastModel.userId = TestUserId;
    binningEastModel.createTime = [[MAAFConfig sharedInstance] getNowTime];
    // 判断数据库中是否已有数据
    if (_binningEastModel) {
        // 指定东向装车数据的ID
        if (_binningEastModel.eastId == 0) {
            // 如果westId = 0,则刚刚保存过,在存储列表的数据最顶端,否则westId不可能等于0
            // 查询保存的最后一条数据
            NSMutableArray *dataArray = [RailTransportDao selectBinningEast:TestUserId];
            if (dataArray.count > 0) {
                BinningEastModel *tmpModel = dataArray[0];
                binningEastModel.eastId = tmpModel.eastId;
            }
        }else{
            // 1.保存列表跳转有westId直接赋值
            // 2.保存后更新数据
            binningEastModel.eastId = _binningEastModel.eastId;
        }
        // 更新东向装车表中数据
        BOOL state = [RailTransportDao updateBinningEast:binningEastModel];
        if (state) {
            // 更新Model,可以根据westId更新本地已保存数据
            _binningEastModel = binningEastModel;
            
            [MBProgressHUD showSuccess:@"更新成功"];
        }else{
            [MBProgressHUD showError:@"更新失败"];
        }
    }else{
        // 添加东向装车表中
        BOOL state = [RailTransportDao addBinningEast:binningEastModel];
        if (state) {
            // 保存Model,可以根据westId更新本地已保存数据
            _binningEastModel = binningEastModel;
            
            [MBProgressHUD showSuccess:@"保存成功"];
        }else{
            [MBProgressHUD showError:@"保存失败"];
        }
    }
}
// 上传按钮 Action
- (IBAction)uploadBtnAction:(UIButton *)sender
{
    // 上传数据检验
    if ([self uploadDataVerify]) {
        // 初始化数组
        NSMutableArray *dataArray = [[NSMutableArray alloc]init];
        // 上传数据JOSN数组
        [dataArray addObject:[self uploadDataDic:[[[self getMerchandiseVIN:self.topStentsBtnOneArray] allKeys]firstObject] racksPallets:self.stentsOneNumber.text vin:[[[self getMerchandiseVIN:self.topStentsBtnOneArray] allValues]firstObject]]];
        [dataArray addObject:[self uploadDataDic:[[[self getMerchandiseVIN:self.bottomStentsBtnOneArray] allKeys]firstObject] racksPallets:self.stentsOneNumber.text vin:[[[self getMerchandiseVIN:self.bottomStentsBtnOneArray] allValues]firstObject]]];
        [dataArray addObject:[self uploadDataDic:[[[self getMerchandiseVIN:self.topStentsBtnTwoArray] allKeys]firstObject] racksPallets:self.stentsTwoNumber.text vin:[[[self getMerchandiseVIN:self.topStentsBtnTwoArray] allValues]firstObject]]];
        [dataArray addObject:[self uploadDataDic:[[[self getMerchandiseVIN:self.bottomStentsBtnTwoArray] allKeys]firstObject] racksPallets:self.stentsTwoNumber.text vin:[[[self getMerchandiseVIN:self.bottomStentsBtnTwoArray] allValues]firstObject]]];
        // 测试上传接口
        //        NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BinningCarVC" ofType:@"json"]];
        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:[JSONTransition toJSONData:dataArray] options:NSJSONReadingAllowFragments error:nil];
        [NetWorkManager postUploadJOSNWithUrl:[NSString stringWithFormat:@"%@/cetmsplat/shipping/handleShipping",kBaseUrl] params:info tag:self successBlock:^(NSDictionary *dictObject) {
            //返回 codes 解析
            NSNumber *responseCode = [dictObject objectForKey:@"retcode"];
            if (responseCode.intValue == 1) {
                [MBProgressHUD showSuccess:dictObject[@"retmsg"]];
            }else{
                [MBProgressHUD showError:@"上传失败"];
            }
        } failureBlock:^(NSError *error) {
            [MBProgressHUD showError:@"上传失败"];
        }];
    }
}

#pragma mark - dataHandle
// 选择状态按钮
- (void)selectStateBtn:(UIButton *)selectBtn type:(NSInteger)type
{
    // 取消选择
    if (selectBtn.selected) {
        switch (type) {
            case 0:{
                [self buttonStateChange:self.topStentsBtnOneArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnOneArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:MayNotUserInteractionEnabled];
                [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                break;
            }
            case 1:{
                // 查询已选择的按钮
                for (int i = 0; i < self.topStentsBtnOneArray.count; i++) {
                    // 数据按钮
                    UIButton *dataBtn = self.topStentsBtnOneArray[i];
                    // 重新设置按钮状态
                    if (dataBtn.selected == NO) {
                        // 恢复按钮状态
                        [self buttonStateChange:self.bottomStentsBtnOneArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:MayNotUserInteractionEnabled];
                        [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                        [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                        // 返回到操作前按钮状态
                        [self buttonStateChange:self.bottomStentsBtnOneArray selectBtn:dataBtn btnStateChange:OtherStateChange userInteractionEnabledState:MayUserInteractionEnabled];
                        [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:dataBtn btnStateChange:OtherStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                        [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:dataBtn btnStateChange:OtherStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                    }
                }
                break;
            }
            case 2:{
                // 根据bottom One取消选中按钮
                [self cancelTwoTopBtnState:self.bottomStentsBtnOneArray selectBtn:selectBtn type:@"1"];
                // 根据top One取消选中按钮
                [self cancelTwoTopBtnState:self.topStentsBtnOneArray selectBtn:selectBtn type:@"2"];
                break;
            }
            default:
                break;
        }
    }else{
        // 进行选择
        selectBtn.selected = NO;
        switch (type) {
            case 0:{
                [self buttonStateChange:self.topStentsBtnOneArray selectBtn:selectBtn btnStateChange:SelfStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnOneArray selectBtn:selectBtn btnStateChange:OtherStateChange userInteractionEnabledState:MayUserInteractionEnabled];
                [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:selectBtn btnStateChange:OtherStateChange userInteractionEnabledState:MayUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:selectBtn btnStateChange:OtherStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                break;
            }
            case 1:{
                [self buttonStateChange:self.bottomStentsBtnOneArray selectBtn:selectBtn btnStateChange:SelfStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:selectBtn btnStateChange:OtherStateChange userInteractionEnabledState:MayUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:selectBtn btnStateChange:OtherStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                break;
            }
            case 2:{
                [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:selectBtn btnStateChange:SelfStateChange userInteractionEnabledState:MayUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:selectBtn btnStateChange:OtherStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
                break;
            }
            default:
                break;
        }
    }
}
// 取消按钮状态—Two Top type:是否需要恢复按钮状态
- (void)cancelTwoTopBtnState:(NSArray *)dataArray selectBtn:(UIButton *)selectBtn type:(NSString *)type
{
    // 查询已选择的按钮
    for (int i = 0; i < dataArray.count; i++) {
        // 数据按钮
        UIButton *dataBtn = dataArray[i];
        // 重新设置按钮状态
        if (dataBtn.selected == NO) {
            if ([type isEqualToString:@"1"]) {
                // 恢复按钮状态
                [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:MayNotUserInteractionEnabled];
                [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:selectBtn btnStateChange:BtnStateNotChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
            }
            // 返回到操作前按钮状态
            [self buttonStateChange:self.topStentsBtnTwoArray selectBtn:dataBtn btnStateChange:OtherStateChange userInteractionEnabledState:MayUserInteractionEnabled];
            [self buttonStateChange:self.bottomStentsBtnTwoArray selectBtn:dataBtn btnStateChange:OtherStateChange userInteractionEnabledState:IgnoreUserInteractionEnabled];
        }
    }
}

// 按钮状态改变
- (void)buttonStateChange:(NSArray *)dataArray selectBtn:(UIButton *)selectBtn btnStateChange:(BtnStateChange)btnStateChange userInteractionEnabledState:(UserInteractionEnabledState)userInteractionEnabledState
{
    for (int i = 0; i < dataArray.count; i++) {
        // 数据按钮
        UIButton *dataBtn = dataArray[i];
        // 判断按钮状态
        if (btnStateChange == SelfStateChange) {
            // 改变按钮状态(其他)
            if (selectBtn.tag != dataBtn.tag) {
                dataBtn.selected = YES;
            }
        }else if (btnStateChange == OtherStateChange) {
            // 改变按钮状态(自己)
            if (selectBtn.tag == dataBtn.tag) {
                dataBtn.selected = YES;
            }
        }else if (btnStateChange == BtnStateNotChange) {
            dataBtn.selected = NO;
        }
        // 判断是否可以交互或者是忽略交互
        if (userInteractionEnabledState == MayUserInteractionEnabled) {
            dataBtn.userInteractionEnabled = YES;
        }else if (userInteractionEnabledState == MayNotUserInteractionEnabled) {
            dataBtn.userInteractionEnabled = NO;
        }
    }
}

#pragma mark - clear button
// 清除按钮状态
- (void)clearBtnState
{
    [self clearBtnState:self.topStentsBtnOneArray];
    [self clearBtnState:self.bottomStentsBtnOneArray];
    [self clearBtnState:self.topStentsBtnTwoArray];
    [self clearBtnState:self.bottomStentsBtnTwoArray];
}
// 清除按钮状态 Array
- (void)clearBtnState:(NSArray *)btnArray{
    for (int i = 0; i < btnArray.count; i++) {
        UIButton *stateBtn = btnArray[i];
        stateBtn.selected = NO;
    }
}

#pragma mark - upload Data Dictionary
// 上传数据校验
- (BOOL)uploadDataVerify
{
    // 校验集装箱编号
    if (JudgeStrEqualNull(self.containerTF.text)) {
        [MBProgressHUD showError:ContainerPrompt];
        return NO;
    }
    // 校验商品车数据
    for (int i = 0 ; i < self.merchandiseLabelArray.count; i++) {
        UILabel *merchandiseCarLabel = self.merchandiseLabelArray[i];
        if ([merchandiseCarLabel.text isEqualToString:DefaultCommercial] || JudgeStrEqualNull(merchandiseCarLabel.text)) {
            [MBProgressHUD showError:CommercialPrompt];
            return NO;
        }
    }
    // 校验集装箱数据
    for (int i = 0; i < self.containerLabelArray.count; i++) {
        UILabel *containerLabel = self.containerLabelArray[i];
        if ([containerLabel.text isEqualToString:[[self.containerDataArray[i] allValues]firstObject]] || JudgeStrEqualNull(containerLabel.text)) {
            if (i == 0) {
                [MBProgressHUD showError:StentsPrompt];
            }else{
                [MBProgressHUD showError:TrayPrompt];
            }
            return NO;
        }
    }
    // 校验GPS数据
    for (int i = 0; i < self.GPSLabelArray.count; i++) {
        UILabel *GPSLabel = self.GPSLabelArray[i];
        if ([GPSLabel.text isEqualToString:DefaultGPS] || JudgeStrEqualNull(GPSLabel.text)) {
            [MBProgressHUD showError:DefaultGPS];
            return NO;
        }
    }
    // 选择个数
    NSInteger selectCount = 0;
    // 校验示意图车辆位置选择数据
    for (int i = 0; i < self.bottomStentsBtnTwoArray.count; i++) {
        UIButton *trayBtn = self.bottomStentsBtnTwoArray[i];
        if (trayBtn.selected == YES) {
            selectCount ++;
        }
        if (selectCount != 2 && i == 2) {
            [MBProgressHUD showError:@"请在示意图中选择车辆摆放顺序"];
            return NO;
        }
    }
    return YES;
}
/*
 *  blockTrain    班列号
 *  containerNo   集装箱编号
 *  direction     列车行驶方向
 *  position      出发地
 *  rackLocation  对应所在支架的位置(1支架 上, 2支架 下, 3托盘)
 *  racksPallets  支架编号
 *  startTime     出发时间  格式:20171124
 *  vin           车辆VIN码
 */
// 上传JSON数据字典
- (NSDictionary *)uploadDataDic:(NSString *)rackLocation racksPallets:(NSString *)racksPallets vin:(NSString *)vin
{
    NSDictionary *dataInfo = @{@"blockTrain":
                                   @"上一版本列车编号",
                               @"containerNo":self.containerTF.text,
                               @"direction":self.trainShiftModel.departDirection,
                               @"position":
                                   self.trainShiftModel.location,
                               @"rackLocation":rackLocation,
                               @"racksPallets":racksPallets,
                               @"startTime":
                                   [self.trainShiftModel.date stringByReplacingOccurrencesOfString:@"-" withString:@""],
                               @"vin":vin};
    return dataInfo;
}

#pragma mark - getMerchandiseVIN
// 获取商品车VIN码
- (NSDictionary *)getMerchandiseVIN:(NSArray *)dataArray
{
    NSInteger dataBtnTag = 0;
    for (int i = 0; i < dataArray.count; i++) {
        // 数据按钮
        UIButton *dataBtn = dataArray[i];
        if (dataBtn.selected == NO) {
            dataBtnTag = dataBtn.tag;
        }
    }
    // 获取商品车
    UILabel *merchandiseCarLabel = self.merchandiseLabelArray[dataBtnTag];
    // 获取商品车VIN码
    NSDictionary *dataInfo = @{[NSString stringWithFormat:@"%ld",dataBtnTag + 1]:
                                   merchandiseCarLabel.text};
    // 返回 Key(所选编号) Value(商品车VIN码)
    return dataInfo;
}

@end
